package com.liujianlei.forum_system.controller;

import com.liujianlei.forum_system.common.AppResult;
import com.liujianlei.forum_system.common.ResultCode;
import com.liujianlei.forum_system.config.AppConfig;
import com.liujianlei.forum_system.exception.ApplicationException;
import com.liujianlei.forum_system.model.Message;
import com.liujianlei.forum_system.model.User;
import com.liujianlei.forum_system.service.IMessageService;
import com.liujianlei.forum_system.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author tongchen
 * @create 2023-08-11 10:38
 */
@Slf4j
@RestController
@RequestMapping("/message")
@Api(tags = "站内信实现")
public class MessageController {
    @Resource
    private IMessageService messageService;
    @Resource
    private IUserService userService;
    @PostMapping("/send")
    @ApiOperation("产生交互信息")
    public AppResult createMessage(HttpServletRequest request, @RequestParam@ApiParam("内容接收者") @NonNull Long receiverId, @RequestParam@ApiParam("文章内容")@NonNull String content){
        //获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User poster = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断当前登录用户对应的状态
        if(poster.getState()==1){
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        //不能发给自己
        if(receiverId==poster.getId()){
            //记录错误日志
            log.error("私信不能发送给自己");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_FORBIDDEN));
        }
        //判断当前用户是否存在
        User user = userService.selectByPrimaryKey(receiverId);
        if(user==null){
            //记录错误信息并抛出异常
            log.error("当前用户不存在");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //判断当前用户的状态
        if(user.getState()==1||user.getDeleteState()==1){
            //当前用户状态异常
            log.error("目标用户状态异常");
            throw new ApplicationException(AppResult.failed("用户状态异常"));
        }
        //创建对象
        Message message = new Message();
        //补充数据
        message.setContent(content);
        message.setReceiveUserId(receiverId);
        message.setPostUserId(poster.getId());
        //将数据插入
        messageService.createMessage(message);
        return AppResult.success("站内信发送成功");
    }
    @GetMapping("/getUnreadCount")
    @ApiOperation("返回未读信息数量")
    public AppResult getUnreadCount(HttpServletRequest request){
        //获取当前session
        HttpSession session = request.getSession(false);
        //获取对应id
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        Long id = user.getId();
        //直接调用service
        int unreadCount = messageService.getUnreadCount(id);
        log.info("查询数量"+unreadCount);
        return AppResult.success("查找成功",unreadCount);
    }
    @ApiOperation("查询所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request){
        //获取session和当前用户
        HttpSession session = request.getSession(false);
        User loginUser = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用方法获取数据
        Long id = loginUser.getId();
        //调用service
        List<Message> messages = messageService.selectByReceiveUserId(id);
        return AppResult.success("所有站内信查询成功",messages);

    }
    @ApiOperation("更新为已读")
    @PostMapping("/markRead")
    public AppResult markRead(HttpServletRequest request,@RequestParam @ApiParam("信息id")@NonNull Long id){
        //检查对应的message是否存在
        Message message = messageService.selectById(id);
        if(message==null||message.getDeleteState()==1){
            log.error("当前数据不存在");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        //判断当前登录用户是否有权查看
        HttpSession session = request.getSession(false);
        User loginUser = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(loginUser.getId()!=message.getReceiveUserId()){
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_UNAUTHORIZED));
        }
        //更新
        messageService.updateStateById(id, (byte) 1);
        //返回结果
        return AppResult.success("信息状态修改成功");
    }
    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,@RequestParam("repliedId")@ApiParam("需要回复信息对应的id")@NonNull Long replyMessageId,
                           @RequestParam@ApiParam("回复信息对应的内容")@NonNull String content){
        //获取当前登录的用户状态,判断用户是否有权进行内容的处理
        HttpSession session = request.getSession(false);
        User loginUser = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(loginUser.getState()==1){
            log.error(ResultCode.FAILED_USER_BANNED.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
        }
        //获取需要回复的信息
        Message message = messageService.selectById(replyMessageId);
        if(message==null||message.getDeleteState()==1){
            log.error("当前信息状态异常");
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_NOT_EXISTS));
        }
        //当前信息不能是自己发给自己的信息
        if(message.getPostUserId()==loginUser.getId()){
            log.error("不能回复自己发给自己的信息");
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_UPDATE));
        }
        //创建信息并进行回复
        Message replyMessage = new Message();
        replyMessage.setContent(content);
        replyMessage.setPostUserId(loginUser.getId());
        replyMessage.setReceiveUserId( message.getPostUserId());

        messageService.reply(replyMessageId,replyMessage);
        return AppResult.success("回复信息成功");

    }

}
